using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class UI_FadeEffect : MonoBehaviour
{
    [SerializeField] private Image fadeImage;
    public Coroutine fadeEffectCo { get; private set; }

    private void Awake()
    {
        fadeImage.color = new(0f, 0f, 0f, 1f);
    }
    public void DoFadeIn(float duration = 1)
    {
        StartFadeRffectCo(0, 1, duration);
    }

    public void DoFadeOut(float duration = 1)
    {
        StartFadeRffectCo(1, 0, duration);
    }
    private void StartFadeRffectCo(float startAlpha, float targetAlpha, float duration)
    {
        if (fadeEffectCo != null)
            StopCoroutine(fadeEffectCo);

        fadeEffectCo = StartCoroutine(FadeEffectCo(startAlpha, targetAlpha, duration));
    }
    private IEnumerator FadeEffectCo(float startAlpha, float targetAlpha, float duration)
    {
        fadeImage.color = new(0, 0, 0, startAlpha);
        float timer = 0;
        Color startColor = fadeImage.color, targetColor = new(0, 0, 0, targetAlpha), color;
        while (timer <= duration)
        {
            timer += Time.deltaTime;

            color = Color.Lerp(startColor, targetColor, timer / duration);
            color.a = Mathf.Clamp(color.a, 0, 1);

            fadeImage.color = color;

            yield return null;
        }
    }
}
